/* eslint-disable n/no-process-exit */
//! VITE_NODE_DEBUG_DUMP=load vite-node scripts/vite-node.mts
import { createServer, version as viteVersion } from "vite";
import { ViteNodeRunner } from "vite-node/client";
import { ViteNodeServer } from "vite-node/server";
import { installSourcemapsSupport } from "vite-node/source-map";
import { p2 } from "../shared/p2.mjs";

// create vite server
const server = await createServer({
  optimizeDeps: {
    // It's recommended to disable deps optimization
    disabled: true,
  },
  env: {
    WATCH_MODE: "1",
  },
});

// For old Vite, this is need to initialize the plugins.
// if (Number(viteVersion.split(".")[0]) < 6) {
//   await server.pluginContainer.buildStart({});
// }
console.assert(
  Number(viteVersion.split(".")[0]) >= 6,
  "Vite version must be >= 6",
);

// create vite-node server
const nodeServer = new ViteNodeServer(server);

// fixes stacktraces in Errors
installSourcemapsSupport({
  getSourceMap: (source) => nodeServer.getSourceMap(source),
});

// create vite-node runner
const runner = new ViteNodeRunner({
  root: server.config.root,
  base: server.config.base,
  // when having the server and runner in a different context,
  // you will need to handle the communication between them
  // and pass to this function
  fetchModule(id) {
    return nodeServer.fetchModule(id);
  },
  resolveId(id, importer) {
    return nodeServer.resolveId(id, importer);
  },
});

// execute the file
await runner.executeFile(p2("postcss/watch-case.mjs"));

process.on("SIGINT", async () => {
  console.log("收到 Ctrl+C，正在退出...");
  // 模拟异步操作
  await server.close();
  // close the vite server
  process.exit(0);
});
